/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package generator.relationships;

import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import net.db.generator.BaseListModel;
import net.db.generator.JavaConnectionClassWriter;
import net.db.generator.JavaConnectionPropertiesWriter;
import net.db.generator.JavaDAOBaseClassWriter;
import net.db.generator.JavaDAOClassWriter;
import net.db.generator.JavaDAOFullClassWriter;
import net.db.generator.field.models.BaseFieldModel;
import net.db.generator.field.models.DataBaseColumnType;
import net.db.generator.field.models.SQLTypeMap;

/**
 *
 * @author abosancic
 */
public class ClassGeneratorReferenceModel extends generator.ClassGenerator {

    /**
     * Creates new form ClassGeneratorReferenceModel
     */
    public ClassGeneratorReferenceModel() {
        initComponents();
        initComponentsCustom();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 822, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 514, Short.MAX_VALUE)
        );

        setSize(new java.awt.Dimension(838, 554));
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    @Override
    protected void generateBtnActionPerformed(java.awt.event.ActionEvent evt) {                                            
        
        if (dbGenList.getModel() != null && dbGenList.getModel() instanceof BaseListModel) {
            String tables = null;
            
            JavaDAOClassWriter dao = new JavaDAOClassWriter();
            dao.setPackageName(jTextFieldDAO.getText());
            dao.setImportPackages(new String[]{
                "net.db.generator.utils.ClassGeneratorUtil",
                "java.io.InputStream",
                "java.io.Serializable",
                "java.lang.reflect.InvocationTargetException",
                "java.lang.reflect.Method",
                "java.math.BigDecimal",
                "java.sql.Connection",
                "java.sql.Date",
                "java.sql.PreparedStatement",
                "java.sql.ResultSet",
                "java.sql.SQLException",
                "java.sql.Time",
                "java.sql.Timestamp",
                "java.util.ArrayList",
                "java.util.List",
                "java.util.logging.Level",
                "net.etfbl.dao.base.IDAOBase",
                "java.util.logging.Logger",
            });
            dao.generateClass();
            
            // write  ConnectionPool class
            if (jConnectionPoolClass.isSelected()) {
                JavaConnectionClassWriter jcon = new JavaConnectionClassWriter();
                jcon.setPackageName(jTextFieldDAO.getText());
                jcon.setImportPackages(new String[]{"java.sql.*", "java.util.*"});
                jcon.generateClass();
            }

            if (jPropertiesFile.isSelected()) {
                JavaConnectionPropertiesWriter jprop = new JavaConnectionPropertiesWriter();
                jprop.setPackageName(jTextFieldDAO.getText());
                jprop.generateFile();
            }
            
            JavaDAOBaseClassWriter daogen = new JavaDAOBaseClassWriter();
            if(jFindRemoveMethods.isSelected())
            {
                daogen = new JavaDAOFullClassWriter();
            }
            daogen.setPackageName(jTextFieldDAO.getText());
//            daogen.setDtoPackageName(jTextFieldDTO.getText());
            
            JavaRelationWriter gen = new JavaRelationWriter();
            
            for (int i = 0; i < dbGenList.getModel().getSize(); i++) {
                List<DataBaseColumnType> columns = new ArrayList<>();
                tables = dbGenList.getModel().getElementAt(i).toString();
                
                List<DataBaseRelationshipsModel> refm = null;// getForeignKeys(tables);
                for (DataBaseRelationshipsModel referenceModel : refm) {
                    System.out.println("ref: " + referenceModel);
                }
                
                
                gen.setClassName(tables);
                gen.setPackageName(jTextFieldDTO.getText());
                gen.setImportPackages(new String[]{jTextFieldDAO.getText()+".*"});
                daogen.setClassName(tables);
                daogen.setPackageName(jTextFieldDAO.getText());
//                daogen.setDtoPackageName(jTextFieldDTO.getText());
                
//                BaseListModel dbcolumns = new BaseListModel(getAllColumns(dbList.getSelectedValue().toString(), tables));
//                for (int j = 0; j < dbcolumns.getSize(); j++) {
//                    columns.add(DataBaseColumnType.toModel(dbcolumns.getElementAt(j).toString()));
//                }
                
                
                List<BaseFieldModel> models = new ArrayList<>();
                for (DataBaseColumnType dataBaseColumnType : columns) {
                    models.add(new BaseFieldModel(dataBaseColumnType.getName(), SQLTypeMap.convert(dataBaseColumnType.getType())));
                }
                
                gen.setFields(models.toArray(new BaseFieldModel[models.size()]));
                gen.setReferenceModel(refm.toArray(new DataBaseRelationshipsModel[refm.size()]));
                gen.generateClass();
//                daogen.setUniqueField(getPrimaryKeyName(tables));
                daogen.setFields(models.toArray(new BaseFieldModel[models.size()]));
                daogen.generateClass();
            }

            //System.out.println("Generete complite !!!");
            
            JOptionPane.showMessageDialog(null, "Generating successfully completed.", "Class generator", JOptionPane.INFORMATION_MESSAGE);
            
        }
        
    }
    
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ClassGeneratorReferenceModel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ClassGeneratorReferenceModel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ClassGeneratorReferenceModel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ClassGeneratorReferenceModel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ClassGeneratorReferenceModel().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables

    private void initComponentsCustom() {
        
    }
}
